package netty.demo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ClientHandler extends SimpleChannelInboundHandler<String> {
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 发送测试消息
        sendMessage(ctx,"Hello Server");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        System.out.println("Received from server: " + msg);
        cancelTimeoutTask(); // 取消超时任务
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    // 超时任务管理
    private ScheduledFuture<?> timeoutFuture;

    private void sendMessage(ChannelHandlerContext ctx, String msg) {
        timeoutFuture = scheduler.schedule(() -> {
            System.out.println("请求超时，未收到服务器响应");
            ctx.close();
        }, 5, TimeUnit.SECONDS);

        ctx.writeAndFlush(msg);
    }

    private void cancelTimeoutTask() {
        if (timeoutFuture != null) {
            timeoutFuture.cancel(true);
        }
    }
}